package View;

import java.awt.BorderLayout;
import java.awt.image.ImageObserver;
import java.text.DateFormat;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Controller.Controller;
import Controller.Model;
import eNodeB.Fabrique;

public class SimulationPanel extends JPanel implements Observer {
	private static final long serialVersionUID = 1L;
	private final Controller _ctrl;
	private final Model _m;
	private final ImageIcon _tile;
	private final JButton _pause = new JButton("Start");
	private final JPanel _panButtons;
	private final MapPanel _panMap;
	private final DataPanel _panData;
	private final JLabel _horloge = new JLabel();

	public SimulationPanel(Controller ctrl, Model m) {
		this.setLayout(new BorderLayout());
		_ctrl = ctrl;
		_m = m;
		_m.addObserver(this);
		_tile = new ImageIcon(this.getClass().getResource("/Images/tile.jpg"));
		_panButtons = createButtons();
		_panMap = createMap(_tile);
		_panData = createData();
		_horloge.setText("Empty");
		Fabrique.getFabrique().getEnodeB().getHorloge().addObserver(this);
		add(_panData, BorderLayout.EAST);
		add(_horloge, BorderLayout.NORTH);
		add(_panButtons, BorderLayout.SOUTH);
		add(_panMap, BorderLayout.CENTER);
	}

	private MapPanel createMap(ImageIcon tile) {
		return new MapPanel(tile);
	}

	private JPanel createButtons() {
		JPanel pan = new JPanel();

		_pause.addActionListener(_ctrl);
		_pause.setActionCommand("Start");
		pan.add(_pause);

		return pan;
	}

	private DataPanel createData() {
		return new DataPanel(ImageObserver.HEIGHT);
	}

	public void replacePauseButton() {
		_pause.setVisible(false);
		_pause.setActionCommand("Restart");
		_pause.setText("Restart");
		_panButtons.repaint();
	}

	public void replaceRestartButton() {
		_pause.setVisible(false);
		_pause.setActionCommand("Pause");
		_pause.setText("Pause");
		_panButtons.repaint();
	}

	public MapPanel getMapPanel() {
		return _panMap;
	}

	public JPanel getButtonsPanel() {
		return _panButtons;
	}

	@Override
	public void update(Observable arg0, Object arg1) {

		DateFormat dateFormat = DateFormat.getDateTimeInstance(
				DateFormat.SHORT, DateFormat.MEDIUM);
		String millis = String.valueOf(Fabrique.getFabrique().getEnodeB()
				.getHorloge().getactualTime().getTimeInMillis());
		String s = dateFormat.format(Fabrique.getFabrique().getEnodeB()
				.getHorloge().getactualTime().getTime());
		s = s + ":" + millis.substring(millis.length() - 3);
		_horloge.setText(s);
		this.repaint();

	}
}
